<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>Hello World</title>
  <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
  <style>
    .light{
      color:white;
    }
    .dark{
      color:red;
    }
  </style>
</head>

<body>
  <div id="root"></div>
  <script type="text/babel">

    const themes = {
      light:{
        foreground:'#ffffff',
        background:'#222222'
      },
      dark:{
        foreground:'#000000',
        background:'#eeeeee'
      }
    };

    const ThemeContext = React.createContext(themes.dark);

    function ThemedButton(props){
      return (
        <ThemeContext.Consumer>
          {theme => <button {...props} style={{backgroundColor:theme.background,color:theme.foreground}}/>}
        </ThemeContext.Consumer>
      );
    }

    function Toolbar(props){
      return (
        <div>
          <ThemedButton onClick={props.changeTheme}>
            Change Theme
          </ThemedButton>
        </div>
      );
    }

    class App extends React.Component{
      constructor(props){
        super(props);
        this.state = {
          theme:themes.light
        };

        this.toggleTheme = ()=>{
          this.setState(state => 
            ({theme: (state.theme === themes.dark ? themes.light : themes.dark)})
          );  
        };
         // this.toggleTheme = this.toggleTheme.bind(this);
      }

      // 编写箭头函数的时候，注意如有返回值应使用()包起
      // toggleTheme(){
      //   this.setState(state => 
      //     ({theme: (state.theme === themes.dark ? themes.light : themes.dark)})
      //   );

        // this.setState(function(prevState){
        //   var state = {theme: (prevState.theme === themes.dark ? themes.light : themes.dark)};
        //   return state;
        // });
      // };

      render(){
        return (
          <div>
              <ThemeContext.Provider value={this.state.theme}>
                  <Toolbar changeTheme={this.toggleTheme}/>    
              </ThemeContext.Provider>
              <ThemedButton>default theme</ThemedButton>
          </div>
          
        );
        
        
      }
    }

    ReactDOM.render(<App/>,document.getElementById('root'));
  </script>
  <!--
      Note: this page is a great way to try React but it's not suitable for production.
      It slowly compiles JSX with Babel in the browser and uses a large development build of React.

      To set up a production-ready React build environment, follow these instructions:
      * https://reactjs.org/docs/add-react-to-a-new-app.html
      * https://reactjs.org/docs/add-react-to-an-existing-app.html

      You can also use React without JSX, in which case you can remove Babel:
      * https://reactjs.org/docs/react-without-jsx.html
      * https://reactjs.org/docs/cdn-links.html
    -->
</body>

</html>